﻿@page "/add/{id:long?}"
@using ShopManagment.Models
@using ShopManagment.Service.IService
@rendermode InteractiveServer
@inject IProductService ProductService
@inject IMessageService MessageService
@inject NavigationManager _NavigationManager


<PageTitle>@btnOperation</PageTitle>

    <h1>@btnOperation</h1>


<EditForm Model="product" OnSubmit="Submit">
    <div>
        商品名称：
        <InputText @bind-Value="product!.ProductName" />
    </div>
    <div>
        商品描述：
        <InputText @bind-Value="product!.ProductDescription" />
    </div>
    <Button Type="@ButtonType.Primary" HtmlType="submit">添加</Button>
</EditForm>

@code {

    private string btnOperation = "新增";

    [Parameter]
    public long? id { get; set; }

    public Product product;

    private string res = string.Empty;

    protected override void OnInitialized()
    {
        product = new Product();

        if (id.HasValue)
        {
            btnOperation = "编辑";
        }
    }



    private void Submit()
    {
        if (id.HasValue)
        {
            var item = ProductService.GetById(id);
            item.ProductDescription = product.ProductDescription;
            item.ProductName = product.ProductName;
            ProductService.Update(item);
            res = $"{product.ProductName} 编辑成功 {DateTime.Now}";
            MessageService.Success($"{product.ProductName} 编辑成功 {DateTime.Now}");
        }
        else
        {
            product.ProductId = new Random().Next(6, 10);
            ProductService.Add(product);
            res = $"{product.ProductName} 增加成功 {DateTime.Now}";
            MessageService.Success($"{product.ProductName} 新增成功 {DateTime.Now}");
        }
        _NavigationManager.NavigateTo("list");
    }

}